package com.core.common.manger.storage;

import cn.hutool.core.io.FileUtil;
import com.core.common.cons.FileTypeEnum;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * @author hl
 * @version 1.0.0
 * @ClassName StorageLocalImpl.java
 * @Description 类描述
 * @createTime 2023年05月05日 10:39:00
 */
@Slf4j
@Data
public class StorageLocal implements IStorageRealm {
    private String active="Local";
    private String storagePath;
    private String address;




    @Override
    public FileMate store(byte[] data, String fileSuffixName) {
        FileMate mate=genFilePathMate(getFileDir(fileSuffixName),fileSuffixName);
        FileUtil.writeBytes(data,mate.getFilePath());
        mate.setFileUrl(address+"/"+mate.getFileDir()+mate.getFileKey());
        return mate;
    }






    @Override
    public FileMate store(InputStream inputStream,  String keyName, long contentLength) {
        FileMate mate=genFilePathMate(getFileDir(keyName),keyName);
        FileUtil.writeFromStream(inputStream,mate.getFilePath());
        mate.setFileUrl(address+"/"+mate.getFileDir()+mate.getFileKey());
        return mate;
    }



    @Override
    public Path load(String filename) {
        return null;
    }

    @Override
    public Resource loadAsResource(String filename) {
        try {
            Path file = load(filename);
            Resource resource = new UrlResource(file.toUri());
            if (resource.exists() || resource.isReadable()) {
                return resource;
            } else {
                return null;
            }
        } catch (MalformedURLException e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    @Override
    public void delete(String filename) {
        Path file = load(filename);
        try {
            Files.delete(file);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    private String getFileDir(String fileSuffixName){
        for (FileTypeEnum value : FileTypeEnum.values()) {
            if (value.getFileType().contains(fileSuffixName)){
                return value.getFileTypeCode();
            }
        }
        return null;
    }

}
